package com.the9tcat.everydayapp.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.the9tcat.everydayapp.config.AppConfig;
import com.the9tcat.everydayapp.data.AppInfo;
import com.the9tcat.everydayapp.data.Common;
import com.the9tcat.everydayapp.db.AppDatabase;

public class SyncDailyApp {
	
	public static void syncDailyApp(Context con, AppParams params) {
		List<AppInfo> infos = getDailyApps(params);
		if (infos == null) {
			return;
		}
		for (AppInfo info : infos) {
			boolean result = AppDatabase.saveAppInfo(con, info);
			if (result) {
				// 同步完成一个，发出通知更新
				Intent intent = new Intent(Common.ACTION_SYNC_SUCCEED);
				con.sendBroadcast(intent);
			}
		}
	}
	
    private static List<AppInfo> getDailyApps(AppParams params) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(AppConfig.API_URL);
        try {
            List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
            postData.add(new BasicNameValuePair("day", params.day));
            postData.add(new BasicNameValuePair("age", params.age));
            postData.add(new BasicNameValuePair("sex", params.sex));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData);
            post.setEntity(entity);
            HttpResponse response = client.execute(post);
            InputStream is = response.getEntity().getContent();
            String result = Common.stringFromStream(is);
            Log.d("***", result);
            return parseAppJsonData(result);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private static List<AppInfo> parseAppJsonData(String jsonStr) {
        List<AppInfo> list = new ArrayList<AppInfo>();
        
        try {
            JSONObject json = new JSONObject(jsonStr);
            boolean result = json.getBoolean("result");
            if (!result) {
                return null;
            }
            JSONArray data = json.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                AppInfo info = new AppInfo();
                JSONObject obj = (JSONObject) data.get(i);
                info.id = obj.getString("id");
                info.name = obj.getString("name");
                info.description = obj.getString("description");
                info.icon_url = obj.getString("icon");
                info.pack_name = obj.getString("pack_name");
                info.sex = Common.GENDER[obj.getInt("sex")];
                info.category_id = obj.getInt("category_id");
                info.category_name = obj.getString("category_name");
                info.recommend = obj.getInt("recommend");
                info.user_point = obj.getString("user_point");
                info.user_point_time = obj.getString("user_point_time");
                info.down_time = obj.getString("down_time");
                info.pass = obj.getString("pass");
                info.target_user |= obj.getInt("baby") == 1? 0: Common.BABY;
                info.target_user |= obj.getInt("child") == 1? 0: Common.CHILD;
                info.target_user |= obj.getInt("young") == 1? 0: Common.YOUNG;
                info.target_user |= obj.getInt("adult") == 1? 0: Common.ADULT;
                info.target_user |= obj.getInt("old") == 1? 0: Common.OLD;
                JSONArray down_link = obj.getJSONArray("down_link");
                AppInfo.DownloadLink[] dl = new AppInfo.DownloadLink[down_link.length()];
                for (int j = 0; j < down_link.length(); j++) {
                    JSONObject o = (JSONObject) down_link.get(i);
                    AppInfo.DownloadLink d = new AppInfo.DownloadLink();
                    d.id = o.getInt("id");
                    d.market = o.getString("market");
                    d.link = o.getString("link");
                    d.down_time = o.getString("down_time");
                    dl[j] = d;
                }
                info.down_link = dl;
                JSONArray preview = obj.getJSONArray("preview");
                JSONObject o = (JSONObject) preview.get(0);
                info.screenshot_url = o.getString("addr");
                list.add(info);
            }
        } catch (JSONException e) {
            return null;
        }
        return list;
    }
    
    public static void getCategory() {
        String url = "http://gifthello.com/open/daily/category";
        try {
            HttpURLConnection hc = (HttpURLConnection) new URL(url).openConnection();
            InputStream is = hc.getInputStream();
            String result = Common.stringFromStream(is);
            try {
                JSONObject json = new JSONObject(result);
                JSONArray data = json.getJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
//                    JSONObject obj = (JSONObject) data.get(i);
//                    Log.d("***", obj.getString("id") + " -- " + obj.getString("name"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
